﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using NHibernate.Context;
using System.ServiceModel;
using NHibernate;
using System.ServiceModel.Channels;
using System.ComponentModel;
using MSH.Common.Helpers;

namespace MSH.Server.Webservice
{
    public sealed class NHibernateWcfContextInitializer

            : IDispatchMessageInspector
    {
        private static readonly ISessionFactory s_sessionFactory = NHibernateHelper.GetSessionFactory();

        public Object AfterReceiveRequest(

            ref Message request,

            IClientChannel channel,

            InstanceContext instanceContext)
        {
            CurrentSessionContext.Bind(

               s_sessionFactory.OpenSession());
            return null;
        }

        public void BeforeSendReply(

            ref Message reply,

            Object correlationState)
        {
            var session = CurrentSessionContext.Unbind(

                 s_sessionFactory);


            session.Dispose();
        }
    }
}
